package com.example.smartf.mqtt;

import com.example.smartf.model.MqttCustionMap.SingleMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DownHandler {
    //日志记录器
    private Logger logger = LoggerFactory.getLogger(getClass());

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public String sendDownMesg(String deviceId,String usern,String message){
        lock.lock();

        DownMqtt mqtt = new DownMqtt();
        //设置对应用户
        mqtt.setUsername(usern);
        //设置条件变量和锁
        mqtt.setLockAndCondition(lock,condition);
        //
        mqtt.setSub_topic(deviceId+"_back");
        //mqtt连接，连接同时订阅 deviceid_back响应主题
        mqtt.connect();
        //连接后，发送下行控制
        mqtt.publish(deviceId + "_control",message);
        //阻塞等待 响应主题的回调 发送信号量唤醒
        try{
            //等待响应5秒
            condition.await(5, TimeUnit.SECONDS);
        }catch (InterruptedException e){
            mqtt.disconnect();
            logger.warn("下行--condition await 发生异常！");
            return "recvice error";
        }
        mqtt.disconnect();

        lock.unlock();

        //接受数据成功，已存入singlemap，取出数据
        SingleMap singleMap = SingleMap.getInstance();
        String res = singleMap.get(usern);
        //等待后 若res为空，则无响应
        if(null == res){
            logger.warn("下行--接受数据超时");
            return "time out";
        }
        //有数据则删除表内数据  并  返回结果
        singleMap.delete(usern);
        return res;

    }
}
